package logic

import (
	"context"
	"fmt"
	"register/model/cache"
	"register/model/mysql"
	"register/pkg"
	"register/registerRpc/internal/svc"
	"register/registerRpc/registerRpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type RegisterUserLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewRegisterUserLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RegisterUserLogic {
	return &RegisterUserLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *RegisterUserLogic) RegisterUser(in *registerRpc.RegisterUserRequest) (*registerRpc.RegisterUserResponse, error) {
	// todo: add your logic here and delete this line

	var data mysql.User
	mysql.DB.Where("account=?", in.Account).Find(&data)
	if data.ID != 0 {
		return nil, fmt.Errorf("该账号已被注册,请重新输入账号")
	}

	cacheKey, _ := cache.Rdb.Get(l.ctx, "SmsKey"+in.Account).Result()
	if in.SmsCaptcha != cacheKey {
		return nil, fmt.Errorf("短信验证码错误,请重新输入")
	}

	user := mysql.User{
		Account:    in.Account,
		Password:   pkg.Md5str1(in.Password),
		Captcha:    in.Captcha,
		SmsCaptcha: in.SmsCaptcha,
	}
	mysql.DB.Create(&user)
	return &registerRpc.RegisterUserResponse{
		UserId: int64(user.ID),
	}, nil
}
